#!/bin/bash


si=0
set_data() {
    class[$si]="$1"
    name[$si]="$2"
    cmdstr[$si]="$3"
    note[$si]="$4"
    #copytext[$si]="$5"
    si=$(($si+1))
}

# 载入数据
PROJECT_ROOT="$HOME/.config/scripts/fzf-tools"
if [[ -f "$PROJECT_ROOT/databases-cmd.sh" ]]; then
    source "$PROJECT_ROOT/databases-cmd.sh"
# else
#     cp "$PROJECT_ROOT/databases-example.sh" "$PROJECT_ROOT/databases.sh"
#     # [ -f ./databases.sh ] && source ~/.config/scripts/fzf-sshscp/databases.sh
#     source "$PROJECT_ROOT/databases-example.sh"
fi

_list() {
    for ((i = 0; i < ${#class[@]}; i++)); do
        _item=${class[$i]}" : "${name[$i]}" "${cmdstr[$i]}" "${note[$i]}
        echo "${_item[@]}"
    done
}

_index() {
    for ((i = 0; i < ${#class[@]}; i++)); do
         _item=${class[$i]}" : "${name[$i]}" "${cmdstr[$i]}" "${note[$i]}
        [[ "$_item" == "$1" ]] && echo $i && break
    done
}

_preview1() {
    index=$(_index "$1")
    echo  ${note[index]}
    echo  ${cmdstr[index]}
}

_cmdstr() {
    index=$(_index "$1")
    echo  ${cmdstr[index]}
}

_copytext() {
    index=$(_index "$1")
    echo -n "${cmdstr[index]}"
}



_cmd() {
    # linux
    # cmd=$(_list | fzf \
    #     --cycle \
    #     --header='请选择服务器(tab复制地址、Esc退出)' \
    #     --header-first \
    #     --bind='tab:execute(h=$(~/.config/scripts/fzf-tools/ssh.sh cmdstr {}) && lemonade copy $h && echo $h  | xsel -b)+abort' \
    #     --preview="~/.config/scripts/fzf-tools/cmd.sh preview1 {}" \
    #     --height=10 \
    #     --preview-window=bottom:2:wrap
    # )
    # macOS
    cmd=$(_list | fzf \
        --cycle \
        --header='请选择命令(tab复制、Esc退出)' \
        --header-first \
        --bind='tab:execute(h=$(~/.config/scripts/fzf-tools/cmd.sh cmdstr {}) && echo $h | pbcopy)+abort' \
        --preview="~/.config/scripts/fzf-tools/cmd.sh preview1 {}" \
        --height=81% \
        --preview-window=bottom:2:wrap
    )

    # echo $cmd
    
    [[ -z "$cmd" ]] && exit 0
    [[ -z "$(_index "$cmd")" ]] && echo $cmd && exit 0
    # [[ -z "$(_copytext "$cmd")" ]] && echo $cmd && exit 0
    # 复制  到剪贴板
    echo -e "copy $(_copytext "$cmd") ..."
    echo -e "copy "$cmd"  ..."
    echo -e "$(_copytext "$cmd")" | pbcopy  
    echo -e "copy success."

    # 执行连接命令
    # echo -e "$(_preview "$server")\nconnecting..."
    # exec $(_preview "$server")

}

case $1 in
    '') _cmd ;;
    preview1) _preview1 "$2" ;;
    cmdstr) _cmdstr "$2" ;;
    copytext) _copytext "$2" ;;
    *) _cmd $* ;;
esac